//
//  XMHomeViewController.swift
//  XMWeimo
//
//  Created by ios001 on 16/7/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
// cell可重用标识符
private let homeCellID = "homeCellID"

class XMHomeViewController: XMVisitorViewController {

    // 全局的模型数组
    var statusListViewModel: XMStatusListViewModel = XMStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !isLogin {
            visitorView?.setupVisitorViewInfo(nil, title: nil)
            return
        }
        
        
        setupTableViewInfo()
        
        getHomeData()
    }
    // 设置tableView
    func setupTableViewInfo(){
        
        navigationController!.view.insertSubview(pullDownTipLabel, belowSubview: navigationController!.navigationBar)
        // 去掉半透明(高斯模糊)状态
        navigationController?.navigationBar.translucent = false
        
        // 设置数据源代理
        tableView.dataSource = self
        tableView.delegate = self
        // 注册cell
        tableView.registerClass(XMStautsCell.self, forCellReuseIdentifier: homeCellID)
        // 去掉分割线
        tableView.separatorStyle = .None
        // 设置tableView 的 cell预估行高(预估越接近真实cell的高度越好)
        tableView.estimatedRowHeight = 200
        //  UITableViewAutomaticDimension
        // 设置tableView footView
        tableView.tableFooterView = indeicaorView
        // 添加刷新控件
        tableView.addSubview(refreshControl)
        // 添加事件
        refreshControl.addTarget(self, action: "refreshAction", forControlEvents: UIControlEvents.ValueChanged)

    }
    
    func refreshAction(){
        getHomeData()
    }
    // MARK: - 懒加载控件
    // 菊花
    private lazy var indeicaorView: UIActivityIndicatorView = {
       let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        // 给菊花设置颜色
        view.color = ThemeColor
        return view
    }()
    
    // 系统下拉刷新
//    private lazy var refreshControl: SHRefreshControl = SHRefreshControl()
    private lazy var refreshControl: XMRefreshControl = XMRefreshControl()
    
    // 请求微博数据提示
    private lazy var pullDownTipLabel: UILabel = {
        let lab = UILabel(textColor: UIColor.whiteColor(), textFont: 12)
        lab.frame = CGRect(x: 0, y: 64 - 30, width: SCREENW, height: 30)
        lab.textAlignment = .Center
        lab.backgroundColor = ThemeColor
        lab.hidden = true
        return lab
    }()
}


// MARK: - UITableViewDataSource
extension XMHomeViewController: UITableViewDataSource,UITableViewDelegate {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusListViewModel.statusList.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(homeCellID, forIndexPath: indexPath) as! XMStautsCell
        // 给cell赋值
        cell.statusViewModel = statusListViewModel.statusList[indexPath.row]
//        // 取消cell选中状态灰色
        cell.selectionStyle = .None
        return cell
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        // 如果判断是最后一个cell的时候,才可以叫菊花转,且当前菊花没有开始动画
        if indexPath.row == statusListViewModel.statusList.count - 1 && !indeicaorView.isAnimating(){
            // 开始动画
            indeicaorView.startAnimating()
            getHomeData()
        }
    }
}

// MARK: - 请求微博数据
extension XMHomeViewController {
    // 请求首页数据
    func getHomeData(){
        
        statusListViewModel.loadHomeData(indeicaorView.isAnimating()) { (isSuc, count) -> () in
            // 停止动画
//            self.indeicaorView.stopAnimating()
            self.endRefreshing()
            if !isSuc {
                print("请求数据失败")
                return
            }
            self.tableView.reloadData()
            if count >= 0 {
                self.setpullDownTipLabelAnim(count)
            }
        }
    }
    
    // MARK: - 设置微博提示动画
    func setpullDownTipLabelAnim(count: Int) {
        // 判断如果当前在动画就是现实 就不再进行动画
        if pullDownTipLabel.hidden == false {
            return
        }
        
        // 显示控件
        pullDownTipLabel.hidden = false
        var name = ""
        if count == 0 {
            name = "已经是最新微博数据"
        }else {
            name = "更新了\(count)条微博"
        }
        // 设置text
        pullDownTipLabel.text = name
        
        // 设置动画
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            self.pullDownTipLabel.transform = CGAffineTransformMakeTranslation(0, 30)
            }) { (_) -> Void in
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                    self.pullDownTipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        // 完成后隐藏
                        self.pullDownTipLabel.hidden = true
                })
        }

    }
    
    // 停止各种动画
    func endRefreshing(){
        self.indeicaorView.stopAnimating()
        self.refreshControl.endRefreshing()
    }
}
